package com.kweative.lingua.server.transport;

import com.kweative.lingua.server.client.Client;
import com.kweative.lingua.server.client.SocketClient;
import com.kweative.lingua.server.request.RequestHandler;
import com.kweative.lingua.server.request.SocketRequestHandler;
import com.kweative.lingua.server.response.ResponseHandler;
import com.kweative.network.Response;
import com.kweative.network.SocketResponse;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */

public class SocketTransport extends Transport {
    protected ServerSocket listener = null;
    protected Class requestClass = SocketRequestHandler.class;
    protected Class responseClass = SocketResponse.class;

    @Override
    protected boolean attach() {
        try {

            listener = new ServerSocket(getPort());
            Logger.getLogger(SocketTransport.class.getName()).log(Level.INFO,String.format("Transport: HTTP Listening on port: %s",getPort()));
            return true;
        } catch (IOException ex) {
            Logger.getLogger(SocketTransport.class.getName()).log(Level.SEVERE, "Transport: Failed to connect HTTP transport", ex);
        }
        return false;
    }

    @Override
    protected Client acceptClient() throws IOException {
        Socket s = listener.accept();
        try {
            
            return new SocketClient((RequestHandler) requestClass.newInstance(),new ResponseHandler((Response) responseClass.newInstance(),null),s);
        } catch (InstantiationException ex) {
            Logger.getLogger(SocketTransport.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(SocketTransport.class.getName()).log(Level.SEVERE, null, ex);
        }
        //Close if failed...
        s.close();
        return null;
    }

    @Override
    protected void detach() {
        if (listener != null) {
            try {
                listener.close();
            } catch (IOException ex) {
                Logger.getLogger(SocketTransport.class.getName()).log(Level.SEVERE, null, ex);
            }
            listener = null;
        }
    }
    
}
